package com.ctshk.rpc.finance.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.finance.dto.stamptax.StampTaxRefundListDTO;
import com.ctshk.rpc.finance.entity.FinanceStampTaxRefund;
import com.ctshk.rpc.finance.excel.ExcelData;
import com.ctshk.rpc.finance.excel.ExcelTemp;
import com.ctshk.rpc.finance.mapper.FinanceStampTaxRefundMapper;
import com.ctshk.rpc.finance.req.stamptax.StampTaxExportOutReq;
import com.ctshk.rpc.finance.req.stamptax.StampTaxRefundAddReq;
import com.ctshk.rpc.finance.req.stamptax.StampTaxRefundListReq;
import com.ctshk.rpc.finance.service.IFinanceStampTaxRefundService;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 印花税退款记录 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-04-05
 */
@DubboService
public class FinanceStampTaxRefundServiceImpl extends ServiceImpl<FinanceStampTaxRefundMapper, FinanceStampTaxRefund> implements IFinanceStampTaxRefundService {

    @Autowired
    private FinanceStampTaxRefundMapper stampTaxRefundMapper;


    /**
     * 列表
     *
     * @param req
     * @return
     */
    @Override
    public Result<PageResponse<StampTaxRefundListDTO>> list(StampTaxRefundListReq req) {
        Page<StampTaxRefundListDTO> iPage = new Page<>(req.getPageNo(), req.getPageSize());
        Page<StampTaxRefundListDTO> page = stampTaxRefundMapper.queryListByCondition(iPage,req);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return Result.success(PageResponse.empty(page.getCurrent()));
        }
        PageResponse<StampTaxRefundListDTO> result = new PageResponse<>(
                page.getRecords(),
                page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()),
                page.getTotal(),
                page.getCurrent(),
                page.getSize());
        return Result.success(result);
    }

    /**
     * 導出未退款申請表
     *
     * @param req
     * @return
     */
    @Override
    public ExcelData exportOut(StampTaxExportOutReq req) {
        if (req.getIdList().size() == 0){
            throw new BusinessException(SystemError.SYS_428,"ID集合");
        }
        //印花税退款列表
        List<FinanceStampTaxRefund> refundList = stampTaxRefundMapper.selectBatchIds(req.getIdList());
        if (refundList != null && refundList.size() > 0){
            ExcelData data = new ExcelData();
            data.setName(DateUtil.fmt(LocalDateTime.now(),"yyyyMMddHHmmss"));
            List<List<String>> title = new ArrayList();
            //设置Excel表头
            List<String> header = setExcelHeader();
            //设置数据
            List<List<Object>> rows = new ArrayList();
            for (FinanceStampTaxRefund refund : refundList) {
                //筛选过滤
                if (Objects.equals(refund.getIsDeleted(),1) || Objects.equals(refund.getRefundStatus(),1) || Objects.equals(refund.getExportStatus(),1)){
                    continue;
                }
                List<Object> row = new ArrayList();
                row.add("D");
                row.add("R");
                row.add(refund.getReceiptNumber());
                row.add(refund.getBusinessType());
                row.add(refund.getProductNumber());
                rows.add(row);
            }
            if (rows.size() == 0){
                throw new BusinessException(SystemError.FINANCE_BILL_17023);
            }
            List<String> top1 = new ArrayList<>();
            top1.add("RECORD_INDICATOR");
            top1.add("LICENSE_NUMBER");
            top1.add("NUMBER_OF_RECORDS");
            title.add(top1);
            List<String> top2 = new ArrayList<>();
            top2.add("H");
            top2.add("350273");
            top2.add(rows.size()+"");
            title.add(top2);
            title.add(header);
            List<Object> end1 = new ArrayList<>();
            end1.add("RECORD_INDICATOR");
            end1.add("NUMBER_OF_RECORDS");
            rows.add(end1);
            List<Object> end2 = new ArrayList<>();
            end2.add("H");
            end2.add(rows.size());
            rows.add(end2);
            data.setTitles(title);
            data.setRows(rows);
            return data;
        }
        return null;
    }

    /**
     * 导入TIC退款结果
     *
     *
     * @param temp
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result exportIn(List<ExcelTemp> temp, Long userId) {
        //处理结果
        if (temp.size() == 0){
            throw new BusinessException(SystemError.FINANCE_BILL_17024);
        }
        List<Long> idList = new ArrayList<>();
        List<FinanceStampTaxRefund> list = new ArrayList<>();
        temp.forEach(taxRefund -> {
            //获取符合条件记录
            QueryWrapper<FinanceStampTaxRefund> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("receipt_number",taxRefund.getReceiptNumber());
            queryWrapper.eq("product_number",taxRefund.getProductNumber());
            queryWrapper.eq("refund_status",0);
            queryWrapper.eq("is_deleted",0);
            FinanceStampTaxRefund refund = stampTaxRefundMapper.selectOne(queryWrapper);
            if (refund != null){
                //更新退款状态
                refund.setRefundStatus(1);
                refund.setModifiedId(userId);
                list.add(refund);
                idList.add(refund.getId());
            }
        });
        //批量更新
        if (list.size() > 0){
            boolean updateBatch = updateBatchById(list);
            if (!updateBatch){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        return Result.success(idList);
    }

    /**
     * 新增印花税退款记录（内部接口）
     *
     * @param reqList
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(List<StampTaxRefundAddReq> reqList,Long userId) {
        List<FinanceStampTaxRefund> list = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (StampTaxRefundAddReq req : reqList){
           /* QueryWrapper<FinanceStampTaxRefund> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("refund_number",req.getRefundNumber());
            queryWrapper.eq("business_type",req.getBusinessType());
            queryWrapper.eq("is_deleted",0);
            FinanceStampTaxRefund refund = stampTaxRefundMapper.selectOne(queryWrapper);
            if (refund != null){
                continue;
            }*/
            FinanceStampTaxRefund refund = EntityUtil.copy(req,FinanceStampTaxRefund.class);
            refund.setId(SnowflakeIdWorker.nextId());
            refund.setRefundStatus(0);
            refund.setExportStatus(0);
            refund.setGmtCreate(now);
            refund.setCreateId(userId);
            refund.setIsDeleted(0);
            list.add(refund);
        }
        if (list.size() > 0){
            Integer batch = stampTaxRefundMapper.insertBatchSomeColumn(list);
            if (batch < list.size()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        return Result.success();
    }

    /**
     * 设置Excel表头
     * @return
     */
    private List<String> setExcelHeader() {
        List<String> header = new ArrayList();
        header.add("RECORD_INDICATOR");
        header.add("RECEIPT_NUMBER_IND");
        header.add("RECEIPT_NUMBER");
        header.add("TYPE_OF_REFUND");
        header.add("REFERENCE_NO");
        return header;
    }


}
